<template>
  <div class="p-4">
    <BasicTable @register="registerTable" @fetch-success="onFetchSuccess">
      <template #toolbar>
        <el-button type="primary" @click="handleCreate">新增账号</el-button>
      </template>
      <template #enabled="{ record }">
        <el-switch v-model="record.state" inline-prompt active-text="激活" inactive-text="禁用" />
      </template>
      <template #roles="{ record }">
        <el-tag v-for="item in record.roles" :key="item.id" :type="getRoleType(item.level)" class="mr-1" effect="dark"
          round>
          {{ item.name }}
        </el-tag>
      </template>
      <template #action="{ record }">
        <TableAction :actions="[
          {
            icon: 'info-standard-line|svg',
            tooltip: '查看用户详情',
            color: '#409eff',
            onClick: handleView.bind(null, record)
          },
          {
            icon: 'note-edit-line|svg',
            tooltip: '编辑用户资料',
            color: '#409eff',
            onClick: handleEdit.bind(null, record)
          },
          {
            icon: 'delete-outlined|svg',
            color: '#f56c6c',
            tooltip: '删除此账号',
            popConfirm: {
              title: '是否确认删除',
              okText: '确认',
              cancelText: '取消',
              confirm: handleDelete.bind(null, record)
            }
          }
        ]" />
      </template>
    </BasicTable>
    <UserModal @register="registerModal" @success="handleSuccess" />

  </div>
</template>

<script setup lang="ts">
import { deleteUserById, getUserListByPage } from '@/api/system/user'
import { BasicTable, useTable, TableAction } from '@/components/Table'
import { useGo } from '@/hooks/web/usePage';
import { Recordable } from '/#/global'
import UserModal from './UserModal.vue';
import { useModal } from '@/components/Modal';
import { columns, searchFormSchema } from './user.data2';
import { ElMessage } from 'element-plus';
// import userUserData from './user.data';


const go = useGo();
// const { columns, searchFormSchema } = userUserData()

const [registerTable, { reload, updateTableDataRecord, deleteTableDataRecord }] = useTable({
  title: '用户列表',
  api: getUserListByPage,
  rowKey: 'id',
  columns,
  formConfig: {
    labelWidth: 120,
    schemas: searchFormSchema,
    // autoSubmitOnEnter: true
  },
  highlightCurrentRow: true,
  useSearchForm: true,
  showTableSetting: true,
  border: true,
  handleSearchInfoFn(info) {
    console.log('handleSearchInfoFn', info)
    return info
  },
  actionColumn: {
    id: 'action',
    width: 160,
    label: '操作',
    slots: { customRender: 'action' }
  }
})
const [registerModal, { openModal }] = useModal();

function onFetchSuccess() {
  ElMessage({
    message: '加载表格数据成功',
    type: 'success',
  })
}

function handleCreate() {
  openModal(true, {
    isUpdate: false,
  });
}

function handleView(record: Recordable) {
  go('/system/userDetail/' + record.id);
}
async function handleDelete(record: Recordable) {
  await deleteUserById(record.id)
  deleteTableDataRecord(record.id)
  ElMessage({
    message: `删除用户${record.username}成功`,
    type: 'success',
  })
}
function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
  });
}

function handleSuccess({ isUpdate, values }: Recordable) {
  if (isUpdate) {
    // 演示不刷新表格直接更新内部数据。
    // 注意：updateTableDataRecord要求表格的rowKey存在于每一行的record的keys中
    const result = updateTableDataRecord(values.id, values);
    ElMessage({
      message: isUpdate ? `${values.username}更新成功` : `${values.username}新增成功,初始密码123456`,
      type: 'success',
    })
  } else {
    reload();
  }
}

type type = "" | "info" | "success" | "warning" | "danger"

const getRoleType = (level: number): type => {
  const type: string[] = ['danger', 'success', 'warning', 'info']

  if (level >= type.length) {
    return ''
  } else {
    return type[level] as type
  }
}
</script>
